import { defineStore } from 'pinia';
import { ref } from 'vue';
import { AuthService } from '@/services/auth.service';
import { logger } from '@/utils/logger';

export const useUserStore = defineStore('user', () => {
  const isLoggedIn = ref(false);
  const userInfo = ref<{
    openid?: string;
    nickname?: string;
    avatar?: string;
    token?: string;
  }>({});

  const wechatLogin = async () => {
    try {
      logger.log('Starting WeChat login process');
      const loginRes = await uni.login({ provider: 'weixin' });
      if (loginRes.errMsg !== 'login:ok') {
        logger.error('WeChat login failed', loginRes);
        throw new Error('登录失败');
      }

      const { data } = await AuthService.wechatLogin(loginRes.code);
      logger.log('WeChat login successful', data);

      isLoggedIn.value = true;
      userInfo.value = data;
      return data;
    } catch (error) {
      logger.error('Login failed', error);
      uni.showToast({ title: '登录失败', icon: 'none' });
      throw error;
    }
  };

  const logout = () => {
    isLoggedIn.value = false;
    userInfo.value = {};
  };

  return {
    isLoggedIn,
    userInfo,
    wechatLogin,
    logout,
  };
});
